//
//  LJImagePickerController.m
//  相片的选择
//
//  Created by txx on 2019/8/25.
//  Copyright © 2019 刘军. All rights reserved.
//

#import "LJImagePickerController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface LJImagePickerController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>


@property (nonatomic, strong) NSString *alertStr;
@end

@implementation LJImagePickerController
- (void)viewDidLoad {
    [super viewDidLoad];

}

/**
 相册获取图片
 */
- (BOOL)openPhotoLibrary {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return NO;
    }
    self.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString*)kUTTypeImage,nil];
    self.allowsEditing = NO; // 允许简单编辑图片
    self.delegate=self;
    return YES;
}

/**
 相册获取视频
 */
- (BOOL)openVideoLibrary
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return NO;
    }
    self.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString*)kUTTypeMovie,nil];
    self.videoQuality = UIImagePickerControllerQualityTypeMedium;
    self.delegate=self;
    return YES;
}
/**
 拍照
 */
- (void)openCameraForPhotoAndComplexHandler:(void(^)(UIAlertController *alertVC))complexHandler
{
    // 一般情况下用这个判断
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        // 该设备不支持拍照
        self.alertStr=@"该设备不支持拍照";
    }
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        // 前置摄像头不可用
        self.alertStr=@"前置摄像头不可用";
    }
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
        // 后置摄像头不可用
        self.alertStr=@"后置摄像头不可用";
    }
    AVAuthorizationStatus cameraStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (cameraStatus==AVAuthorizationStatusDenied) {
        self.alertStr=@"你拒绝了此APP访问相机的权限，请到设置中开启访问相机的权限";
    }
    
    if (self.alertStr.length>0) {
        UIAlertController *alertVC=[UIAlertController alertControllerWithTitle:@"温馨提示" message:self.alertStr preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }]];
        complexHandler(alertVC);
        return ;
    }
    self.delegate=self;
    self.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString*)kUTTypeImage,nil];
    self.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto; //相机的模式 拍照/摄像
    self.allowsEditing = NO; // 不允许简单编辑图片
}

/**
 录制
 */
- (void)openCameraForVideo:(NSTimeInterval)maxvideoTime complexHandler:(void(^)(UIAlertController *alertVC))complexHandler
{
    // 一般情况下用这个判断
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        // 该设备不支持拍照
        self.alertStr=@"该设备不支持拍照";
    }
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        // 前置摄像头不可用
        self.alertStr=@"前置摄像头不可用";
    }
    if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
        // 后置摄像头不可用
        self.alertStr=@"后置摄像头不可用";
    }
    AVAuthorizationStatus cameraStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (cameraStatus==AVAuthorizationStatusDenied) {
        self.alertStr=@"你拒绝了此APP访问相机的权限，请到设置中开启访问相机的权限";
    }
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus==AVAuthorizationStatusDenied) {
        self.alertStr=@"你拒绝了此APP访问音频的权限，请到设置中开启访问音频的权限";
    }
    if (self.alertStr.length>0) {
        UIAlertController *alertVC=[UIAlertController alertControllerWithTitle:@"温馨提示" message:self.alertStr preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }]];
        complexHandler(alertVC);
        return;
    }
    self.delegate=self;
    self.videoMaximumDuration=maxvideoTime;
    self.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.mediaTypes =  [[NSArray alloc] initWithObjects:(NSString*)kUTTypeMovie,nil];
    self.videoQuality = UIImagePickerControllerQualityTypeMedium;
    self.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo; //相机的模式 拍照/摄像
}

/**
 UIImagePickerController代理 获取到媒体资源
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        // 图片处理
        UIImage *image = info[UIImagePickerControllerOriginalImage];//获取原始照片
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(photoPath:didFinishSaveWithError:contextINfo:), nil);//保存到相簿
        }
        if ([_imagePickerDelegate respondsToSelector:@selector(LJImagePickerController:image:info:)]) {
            [_imagePickerDelegate LJImagePickerController:self image:image info:info];
        }
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        // 视频处理
        NSURL *videoUrl = info[UIImagePickerControllerMediaURL];//视频路径
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([videoUrl path])) {
                UISaveVideoAtPathToSavedPhotosAlbum([videoUrl path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
            }
        }
        UIImage *image = [self get_videoThumbImage:videoUrl];
        if ([_imagePickerDelegate respondsToSelector:@selector(LJImagePickerController:urlStr:videoImage:info:)]) {
            [_imagePickerDelegate LJImagePickerController:self urlStr:info[UIImagePickerControllerMediaURL] videoImage:image info:info];
        }
        
    }
    // 选择图片后手动销毁界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//图片保存到相册之后的回调
- (void)photoPath:(NSString *)path didFinishSaveWithError:(NSError *)error contextINfo:(void *)contextInfo
{
    if (error) {
        // 保存失败
    }else {
        // 处理图片
    }
}
//视频保存到相册之后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        // 保存失败
    }else {
        // 处理视频
        
    }
}

/**
 用户取消操作
 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    手动销毁界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/**
 获取视频时长
 */
- (CGFloat)get_videoTotalWith:(NSURL *)videoURL
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                     forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:videoURL options:opts];
    float second = 0;
    second = urlAsset.duration.value/urlAsset.duration.timescale;
    return second;
}
/**
 获取视频缩略图
 */

- (UIImage *)get_videoThumbImage:(NSURL *)videoURL
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:videoURL options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    CMTime actualTime;
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 600) actualTime:&actualTime error:&error];
    if (error) {
        return nil;
    }
    return [UIImage imageWithCGImage:img];
}

@end
